# frozen_string_literal: true

require_relative '../../../spec_helper'
require 'tempfile'

describe Wpxf::Utility::BodyBuilder do
  let(:subject) { Wpxf::Utility::BodyBuilder.new }

  describe '#add_field' do
    it 'adds a key-value pair to the field list' do
      expect(subject.add_field('foo', 'bar'))
        .to include(type: :normal, value: 'bar')
    end
  end

  describe '#add_file' do
    it 'adds a file to the field list' do
      expect(subject.add_file('foo', 'bar.txt'))
        .to include(type: :file, path: 'bar.txt')

      expect(subject.add_file('bar', 'foo.txt', 'foobar.txt'))
        .to include(type: :file, path: 'foo.txt', remote_name: 'foobar.txt')
    end
  end

  describe '#add_file_from_string' do
    it 'adds a string to be used as a file field' do
      expect(subject.add_file_from_string('foo', 'bar', 'foobar.txt'))
        .to include(type: :mem_file, value: 'bar', remote_name: 'foobar.txt')
    end
  end

  describe '#add_zip_file' do
    it 'adds string based files to be used in generating a zip file' do
      files = { 'foo.txt' => 'bar', 'bar.txt' => 'foo' }
      expect(subject.add_zip_file('zipfile', files, 'remote.zip'))
        .to include(type: :mem_zip, value: files, remote_name: 'remote.zip')
    end
  end

  describe '#create' do
    it 'creates a hash that can be used as a body when making HTTP requests.' do
      files = { 'foo.txt' => 'bar', 'bar.txt' => 'foo' }
      temp_file = Tempfile.new('foo')

      subject.add_field('normal', 'field')
      subject.add_file('file', temp_file)
      subject.add_file_from_string('fakefile', 'contents', 'remote.txt')
      subject.add_zip_file('zip', files, 'remote.zip')

      subject.create do |body|
        expect(body['normal']).to eq 'field'
        expect(body['file']).to be_kind_of File
        expect(body['fakefile']).to be_kind_of File
        expect(body['zip']).to be_kind_of File
      end
    end
  end
end
